<template>
  <div class="planting-management">
    <!-- 顶部标题区域 -->
    <div class="header-section">
      <div class="page-title">
        <h1>种植管理中心</h1>
        <p>全面监控和管理农产品种植全过程</p>
      </div>
    </div>

    <!-- 统计数据卡片区域 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon total-farms">
              <el-icon><House /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ areaCnt || 0 }}</div>
              <div class="stat-label">种植基地</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon active-crops">
              <el-icon><Sunny /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">42</div>
              <div class="stat-label">在种作物</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon harvest-ready">
              <el-icon><Basket /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">8</div>
              <div class="stat-label">待收获作物</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon quality-score">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">98.5%</div>
              <div class="stat-label">品质合格率</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 主要功能区域 -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- 种植地图 -->
        <el-col :span="12">
          <div class="content-card map-card">
            <div class="card-header">
              <h3>种植基地分布</h3>
              <el-button type="text" @click="viewAllFarms">查看全部</el-button>
            </div>
            <div class="card-content">
              <div ref="mapContainer" class="map-container"></div>
            </div>
          </div>
        </el-col>
        
        <!-- 作物生长状态 -->
        <el-col :span="12">
          <div class="content-card growth-card">
            <div class="card-header">
              <h3>作物生长状态</h3>
              <el-select v-model="selectedCropType" placeholder="选择作物类型" size="small">
                <el-option label="全部" value="all"></el-option>
                <el-option label="蔬菜" value="vegetable"></el-option>
                <el-option label="水果" value="fruit"></el-option>
                <el-option label="谷物" value="grain"></el-option>
              </el-select>
            </div>
            <div class="card-content">
              <div ref="growthChart" class="chart-container"></div>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 近期种植计划 -->
        <el-col :span="8">
          <div class="content-card plan-card">
            <div class="card-header">
              <h3>近期种植计划</h3>
              <el-button type="text" @click="addNewPlan">新增</el-button>
            </div>
            <div class="card-content">
              <el-timeline>
                <el-timeline-item
                  v-for="(plan, index) in plantingPlans"
                  :key="index"
                  :timestamp="plan.date"
                  :type="plan.status">
                  {{ plan.title }}
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
        </el-col>
        
        <!-- 农事活动记录 -->
        <el-col :span="8">
          <div class="content-card activity-card">
            <div class="card-header">
              <h3>农事活动记录</h3>
              <el-button type="text" @click="viewAllActivities">查看全部</el-button>
            </div>
            <div class="card-content">
              <div class="activity-list">
                <div v-for="(activity, index) in recentActivities" :key="index" class="activity-item">
                  <div class="activity-icon">
                    <el-icon><Operation /></el-icon>
                  </div>
                  <div class="activity-details">
                    <div class="activity-title">{{ activity.title }}</div>
                    <div class="activity-time">{{ activity.time }} · {{ activity.location }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        
        <!-- 环境监测数据 -->
        <el-col :span="8">
          <div class="content-card environment-card">
            <div class="card-header">
              <h3>环境监测数据</h3>
              <el-button type="text" @click="refreshEnvironmentData">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
            <div class="card-content">
              <div class="environment-metrics">
                <div class="metric-item">
                  <div class="metric-label">温度</div>
                  <div class="metric-value">{{ environmentData.temperature }}°C</div>
                  <div class="metric-status good">适宜</div>
                </div>
                <div class="metric-item">
                  <div class="metric-label">湿度</div>
                  <div class="metric-value">{{ environmentData.humidity }}%</div>
                  <div class="metric-status good">适宜</div>
                </div>
                <div class="metric-item">
                  <div class="metric-label">土壤pH值</div>
                  <div class="metric-value">{{ environmentData.ph }}</div>
                  <div class="metric-status warning">偏酸</div>
                </div>
                <div class="metric-item">
                  <div class="metric-label">光照强度</div>
                  <div class="metric-value">{{ environmentData.light }} lux</div>
                  <div class="metric-status good">充足</div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'
import china from '@/assets/images/datafie/china.json'
import {countArea, listArea} from '@/api/ncpsy/management/area'
import useUserStore from '@/store/modules/user'
const router = useRouter()
const userStore = useUserStore()
// 响应式数据
const mapContainer = ref(null)
const growthChart = ref(null)
const mapChartInstance = ref(null)
const growthChartInstance = ref(null)
const selectedCropType = ref('all')
const areaCnt = ref(null)
const farmLocations = ref([])

// 种植计划数据
const plantingPlans = ref([
  { date: '2023-06-15', title: '夏季蔬菜种植计划', status: 'primary' },
  { date: '2023-06-20', title: '有机水果施肥计划', status: 'success' },
  { date: '2023-06-25', title: '玉米病虫害防治', status: 'warning' },
  { date: '2023-07-01', title: '秋季作物准备', status: 'info' }
])

// 农事活动记录
const recentActivities = ref([
  { title: '番茄浇水施肥', time: '今天 09:30', location: '东区大棚' },
  { title: '黄瓜病虫害防治', time: '昨天 14:20', location: '西区田地' },
  { title: '玉米除草作业', time: '昨天 10:15', location: '南区田地' },
  { title: '草莓采摘', time: '前天 08:00', location: '北区温室' }
])

// 环境监测数据
const environmentData = ref({
  temperature: 26.5,
  humidity: 68,
  ph: 6.2,
  light: 8500
})

// 初始化地图
const initMap = () => {
  if (mapContainer.value) {
    mapChartInstance.value = echarts.init(mapContainer.value)
    echarts.registerMap('china', china)
    
    // 使用响应式数据
    updateMapChart()
  }
}

// 更新地图图表
const updateMapChart = () => {
  if (!mapChartInstance.value) return
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: params => {
        if (params.data) {
          return `${params.name}<br/>${params.data.desc}`
        }
        return params.name
      }
    },
    geo: {
      map: 'china',
      roam: true,
      zoom: 1.2,
      label: {
        show: false
      },
      itemStyle: {
        areaColor: '#e8f5e9',
        borderColor: '#4caf50',
        borderWidth: 1
      },
      emphasis: {
        itemStyle: {
          areaColor: '#c8e6c9'
        }
      }
    },
    series: [
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        data: farmLocations.value,
        symbol: 'pin',
        symbolSize: 25,
        label: {
          show: true,
          position: 'bottom',
          formatter: params => params.name,
          fontSize: 10
        },
        itemStyle: {
          color: '#2e7d32'
        },
        emphasis: {
          symbolSize: 30
        }
      }
    ]
  }
  
  mapChartInstance.value.setOption(option)
}

// 获取种植基地位置数据
const fetchFarmLocations = () => {
  if (!userStore.id) return
  
  // 查询用户的种植基地列表
  listArea({ userId: userStore.id }).then(res => {
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      // 将API返回的数据转换为地图需要的格式
      farmLocations.value = res.rows.map(area => {
        // 如果API返回的地址包含经纬度信息，则使用；否则使用默认坐标
        let coordinates = [116.46, 39.92]; // 默认北京坐标
        
        // 这里可以根据实际API返回的数据结构解析经纬度
        // 假设API返回的数据中有longitude和latitude字段
        if (area.longitude && area.latitude) {
          coordinates = [parseFloat(area.longitude), parseFloat(area.latitude)];
        } else {
          // 如果没有经纬度，可以根据地址名称设置默认坐标
          const defaultCoords = {
            '北京': [116.46, 39.92],
            '上海': [121.48, 31.22],
            '广州': [113.23, 23.16],
            '成都': [104.06, 30.67],
            '西安': [108.95, 34.27]
          };
          
          // 简单匹配地址中的城市名
          for (const city in defaultCoords) {
            if (area.areaAddress && area.areaAddress.includes(city)) {
              coordinates = defaultCoords[city];
              break;
            }
          }
        }
        
        return {
          name: area.areaName || '未命名基地',
          value: coordinates,
          desc: area.areaAddress || '地址信息未提供'
        };
      });
      
      // 更新地图
      updateMapChart();
    } else {
      // 如果没有数据，使用默认数据
      farmLocations.value = [
        { name: '北京种植基地', value: [116.46, 39.92], desc: '有机蔬菜种植基地' },
        { name: '上海种植基地', value: [121.48, 31.22], desc: '精品水果种植基地' },
        { name: '广州种植基地', value: [113.23, 23.16], desc: '热带水果种植基地' },
        { name: '成都种植基地', value: [104.06, 30.67], desc: '有机谷物种植基地' },
        { name: '西安种植基地', value: [108.95, 34.27], desc: '特色农产品种植基地' }
      ];
      updateMapChart();
    }
  }).catch(err => {
    console.error('获取种植基地位置数据失败', err);
    // 使用默认数据
    farmLocations.value = [
      { name: '北京种植基地', value: [116.46, 39.92], desc: '有机蔬菜种植基地' },
      { name: '上海种植基地', value: [121.48, 31.22], desc: '精品水果种植基地' },
      { name: '广州种植基地', value: [113.23, 23.16], desc: '热带水果种植基地' },
      { name: '成都种植基地', value: [104.06, 30.67], desc: '有机谷物种植基地' },
      { name: '西安种植基地', value: [108.95, 34.27], desc: '特色农产品种植基地' }
    ];
    updateMapChart();
  });
};

// 初始化作物生长状态图表
const initGrowthChart = () => {
  if (growthChart.value) {
    growthChartInstance.value = echarts.init(growthChart.value)
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['生长期', '成熟期', '收获期']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['番茄', '黄瓜', '玉米', '草莓', '白菜', '茄子']
      },
      yAxis: {
        type: 'value',
        name: '数量(亩)'
      },
      series: [
        {
          name: '生长期',
          type: 'bar',
          stack: '总量',
          itemStyle: {
            color: '#66bb6a'
          },
          data: [12, 10, 15, 8, 20, 12]
        },
        {
          name: '成熟期',
          type: 'bar',
          stack: '总量',
          itemStyle: {
            color: '#ffb74d'
          },
          data: [8, 6, 10, 5, 12, 8]
        },
        {
          name: '收获期',
          type: 'bar',
          stack: '总量',
          itemStyle: {
            color: '#ef5350'
          },
          data: [5, 4, 8, 3, 10, 6]
        }
      ]
    }
    
    growthChartInstance.value.setOption(option)
  }
}

// 窗口大小变化处理
const handleResize = () => {
  if (mapChartInstance.value) mapChartInstance.value.resize()
  if (growthChartInstance.value) growthChartInstance.value.resize()
}

// 页面方法
const viewAllFarms = () => {
  router.push({ name: 'FarmList' })
}

const addNewPlan = () => {
  router.push({ name: 'AddPlantingPlan' })
}

const viewAllActivities = () => {
  router.push({ name: 'ActivityList' })
}

const refreshEnvironmentData = () => {
  // 模拟刷新环境数据
  environmentData.value = {
    temperature: (Math.random() * 10 + 20).toFixed(1),
    humidity: Math.floor(Math.random() * 20 + 60),
    ph: (Math.random() * 2 + 5.5).toFixed(1),
    light: Math.floor(Math.random() * 3000 + 7000)
  }
}



// 组件挂载时初始化图表
onMounted(() => {
  nextTick(() => {
    initMap()
    initGrowthChart()
    window.addEventListener('resize', handleResize)
    
    // 获取用户种植基地数量
    if (userStore.id) {
      console.log(userStore.id);
      countArea(userStore.id).then(res => {
        console.log(res)
        areaCnt.value = res || 0
      }).catch(err => {
        console.error('获取种植基地数量失败', err)
        areaCnt.value = 0
      })
      
      // 获取种植基地位置数据
      fetchFarmLocations()
    }
  })
})

// 组件卸载前销毁图表实例
onBeforeUnmount(() => {
  if (mapChartInstance.value) mapChartInstance.value.dispose()
  if (growthChartInstance.value) growthChartInstance.value.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.planting-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 140px);
}

/* 顶部标题区域 */
.header-section {
  margin-bottom: 25px;
}

.page-title {
  background: linear-gradient(135deg, #2e7d32, #66bb6a);
  color: white;
  padding: 25px 30px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(46, 125, 50, 0.2);
}

.page-title h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 500;
}

.page-title p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

/* 统计数据卡片 */
.stats-cards {
  margin-bottom: 25px;
}

.stat-card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  height: 100px;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
  font-size: 24px;
}

.total-farms {
  background: linear-gradient(135deg, #2e7d32, #66bb6a);
}

.active-crops {
  background: linear-gradient(135deg, #f57c00, #ffb74d);
}

.harvest-ready {
  background: linear-gradient(135deg, #c62828, #ef5350);
}

.quality-score {
  background: linear-gradient(135deg, #1565c0, #42a5f5);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

/* 内容卡片 */
.content-card {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  height: 350px;
  display: flex;
  flex-direction: column;
}

.card-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.card-content {
  flex: 1;
  padding: 15px 20px;
  overflow: auto;
}

/* 地图卡片 */
.map-container {
  width: 100%;
  height: 260px;
}

/* 图表容器 */
.chart-container {
  width: 100%;
  height: 260px;
}

/* 活动列表 */
.activity-list {
  height: 100%;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.activity-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.activity-icon {
  width: 36px;
  height: 36px;
  background-color: #e8f5e9;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: #2e7d32;
}

.activity-details {
  flex: 1;
}

.activity-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
}

.activity-time {
  font-size: 12px;
  color: #909399;
}

/* 环境监测数据 */
.environment-metrics {
  height: 100%;
}

.metric-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 6px;
}

.metric-item:last-child {
  margin-bottom: 0;
}

.metric-label {
  width: 80px;
  font-size: 14px;
  color: #606266;
}

.metric-value {
  flex: 1;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  text-align: center;
}

.metric-status {
  width: 50px;
  font-size: 12px;
  text-align: center;
  border-radius: 4px;
  padding: 2px 4px;
}

.metric-status.good {
  background-color: #f0f9ff;
  color: #67c23a;
}

.metric-status.warning {
  background-color: #fdf6ec;
  color: #e6a23c;
}

/* 快速操作按钮 */
.quick-actions {
  margin-top: 25px;
  text-align: center;
}

.quick-actions .el-button {
  margin: 0 10px;
  padding: 12px 25px;
  font-size: 15px;
  border-radius: 8px;
}

.quick-actions .el-button--primary {
  background-color: #2e7d32;
  border-color: #2e7d32;
}

.quick-actions .el-button--primary:hover {
  background-color: #1b5e20;
  border-color: #1b5e20;
}

.quick-actions .el-button--success {
  background-color: #43a047;
  border-color: #43a047;
}

.quick-actions .el-button--success:hover {
  background-color: #2e7d32;
  border-color: #2e7d32;
}

/* 时间线样式调整 */
:deep(.el-timeline-item__timestamp) {
  font-size: 12px;
  color: #909399;
}

:deep(.el-timeline-item__content) {
  font-size: 14px;
  color: #303133;
}

/* 选择器样式调整 */
:deep(.el-select) {
  width: 120px;
}
</style>